//
//  PlayMusicVideoView.m
//  段子手
//
//  Created by dllo on 16/3/23.
//  Copyright © 2016年 JokesTeam. All rights reserved.
//

#import "PlayMusicVideoView.h"

@interface PlayMusicVideoView ()

@property (nonatomic, retain) UIView *downView;
@property (nonatomic, retain) UISlider *playTimeSlider; /**< 播放时间进度的slider */
@property (nonatomic, retain) UIButton *fullScreenButton; /**< 全屏 */
@property (nonatomic, retain) UIButton *playOrPauseButton; /**< 左侧小播放或暂停 */
@property (nonatomic, retain) UIButton *buttonTo; /**< 返回按钮 */
@property (nonatomic, retain) UIButton *centerButton; /**< 中心的按钮 */

@property (nonatomic, retain) UILabel *rightSumTimeLabel; /**< 右边总时长 */
@property (nonatomic, retain) UILabel *leftNowTimeLabel; /**< 左边当前播放时长 */

@property (nonatomic, assign) CGFloat totalDuration; /**< 记录总时间 */

@property (nonatomic, assign) BOOL isPlay; /**< 记录播放状态 */
@property (nonatomic, assign) BOOL isHiddenDownView; /**< 记录当前是否显示  进度条 */

@end

@implementation PlayMusicVideoView


#pragma mark - 创建 子视图
- (void)createSubView {
    // 轻拍手势
    [self shoushi];
    
    // 创建下面的view
    [self createDownView];
  
    // 创建button
    [self createButton];
    
    // 创建slider
    [self createSlider];
    
    // 创建显示时间的label
    [self createTimeLabel];
    
    [self performSelector:@selector(dismissdownView) withObject:nil afterDelay:5];
}

- (void)shoushi {
    // 轻拍手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    // 轻拍次数
    tap.numberOfTapsRequired = 1;
    [self addGestureRecognizer:tap];
}

- (void)createTimeLabel {
    
    self.rightSumTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(_playTimeSlider.frame.size.width + _playTimeSlider.frame.origin.x - 100, _playTimeSlider.frame.origin.y + 20, 100, 20)];
    [self.downView addSubview:_rightSumTimeLabel];
    _rightSumTimeLabel.backgroundColor = [UIColor clearColor];
    _rightSumTimeLabel.font = [UIFont systemFontOfSize:12];
    _rightSumTimeLabel.textColor = [UIColor whiteColor];
    _rightSumTimeLabel.textAlignment = NSTextAlignmentRight;
    _rightSumTimeLabel.text = @"00:00";
    
    self.leftNowTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake( _playTimeSlider.frame.origin.x, _playTimeSlider.frame.origin.y + 20, 100, 20)];
    [self.downView addSubview:_leftNowTimeLabel];
    _leftNowTimeLabel.backgroundColor = [UIColor clearColor];
    _leftNowTimeLabel.font = [UIFont systemFontOfSize:12];
    _leftNowTimeLabel.textColor = [UIColor whiteColor];
    _leftNowTimeLabel.textAlignment = NSTextAlignmentLeft;
    _leftNowTimeLabel.text = @"00:00";
}

- (void)createSlider {
    
    self.playTimeSlider = [[UISlider alloc] initWithFrame:CGRectMake(50, 0, self.bounds.size.width - 100, 20)];
    [self.downView addSubview:_playTimeSlider];
    // 小球样式
    [_playTimeSlider setThumbImage:[UIImage imageNamed:@"iconfont-huakuai"] forState:(UIControlStateNormal)];
    // 改变条颜色 左边条颜色
    _playTimeSlider.minimumTrackTintColor = [UIColor whiteColor];
    // 右边条颜色
    _playTimeSlider.maximumTrackTintColor = [UIColor lightGrayColor];
    [_playTimeSlider addTarget:self action:@selector(sliderAction:) forControlEvents:(UIControlEventValueChanged)];
    
    // 该监听播放进度
    [PLAYMUSIC.videoPlay addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        CGFloat duration = CMTimeGetSeconds(PLAYMUSIC.avPlayItem.duration); /**< 获取视频总时间 */
        CGFloat current = CMTimeGetSeconds(PLAYMUSIC.avPlayItem.currentTime);  /**< 获取视频当前时间 */
      
        NSString *currentT = [NSString stringWithFormat:@"%02d:%02d", (int)current / 60, (int)current % 60];
        self.leftNowTimeLabel.text = currentT;
        
        // 记录总时间，slider需要使用
        self.totalDuration = duration;
        self.playTimeSlider.value = current;
        
        if (current >= duration) {
            _isPlay = NO;
            [_playOrPauseButton setBackgroundImage:[UIImage imageNamed:@"iconfont-bofang-2"] forState:(UIControlStateNormal)];
            _centerButton.hidden = NO;
            _downView.hidden = NO;
            self.playTimeSlider.value = 0;
            _leftNowTimeLabel.text = @"00:00";
            [PLAYMUSIC playMovieFromUrl:_songsModel.mvListUrl];
            // 如果是全屏播放，播放结束后，自动回到小屏
            if ([UIDevice currentDevice].orientation != UIDeviceOrientationPortrait) {
                NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
                [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
                _buttonTo.hidden = NO;
                PLAYMUSIC.playerLayer.frame = CGRectMake(0, 0, self.bounds.size.width, self.frame.size.height);
                self.frame = CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight / 3);
                [self createFram];
                
                [_fullScreenButton setBackgroundImage:[UIImage imageNamed:@"iconfont-quanping"] forState:(UIControlStateNormal)];
                // 调用该block显示隐藏的TableView
                self.block();
            }
        }
        
    }];
    
}

- (void)createDownView {
    self.downView = [[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 40, self.bounds.size.width, 40)];
    [self addSubview:_downView];
    _downView.backgroundColor = RGBA(185, 183, 180, 0.5);
}

- (void)createButton {
    // 该button为最上面的buton
    self.buttonTo = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [self addSubview:_buttonTo];
    _buttonTo.frame = CGRectMake(10, 25, 34, 34);
    _buttonTo.backgroundColor = [UIColor clearColor];
    [_buttonTo setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui-4"] forState:(UIControlStateNormal)];
    [_buttonTo addTarget:self action:@selector(buttonToAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.playOrPauseButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [self.downView addSubview:_playOrPauseButton];
    _playOrPauseButton.frame = CGRectMake(15, 10, 20, 20);
    [_playOrPauseButton setBackgroundImage:[UIImage imageNamed:@"iconfont-suopingzanting"] forState:(UIControlStateNormal)];
    [_playOrPauseButton addTarget:self action:@selector(playOrPauseButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.fullScreenButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [self.downView addSubview:_fullScreenButton];
    _fullScreenButton.frame = CGRectMake(self.frame.size.width - 35, 10, 20, 20);
    [_fullScreenButton setBackgroundImage:[UIImage imageNamed:@"iconfont-quanping"] forState:(UIControlStateNormal)];
    [_fullScreenButton addTarget:self action:@selector(fullScreenButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.centerButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [self addSubview:_centerButton];
    _centerButton.frame = CGRectMake(0, 0, 50, 50);
    _centerButton.center = self.center;
    [_centerButton setBackgroundImage:[UIImage imageNamed:@"iconfont-bofang-2"] forState:(UIControlStateNormal)];
    [_centerButton addTarget:self action:@selector(centerButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    _centerButton.hidden = YES;
}

// 横屏时调用 该方法
- (void)createFram {
    self.downView.frame = CGRectMake(0, self.bounds.size.height - 40, self.bounds.size.width, 40);
    _playOrPauseButton.frame = CGRectMake(15, 10, 20, 20);
    _fullScreenButton.frame = CGRectMake(self.frame.size.width - 35, 10, 20, 20);
    self.playTimeSlider.frame = CGRectMake(50, 0, self.bounds.size.width - 100, 20);
    self.rightSumTimeLabel.frame = CGRectMake(_playTimeSlider.frame.size.width + _playTimeSlider.frame.origin.x - 100, _playTimeSlider.frame.origin.y + 20, 100, 20);
    self.leftNowTimeLabel.frame = CGRectMake( _playTimeSlider.frame.origin.x, _playTimeSlider.frame.origin.y + 20, 100, 20);
    _centerButton.frame = CGRectMake(0, 0, 50, 50);
    _centerButton.center = self.center;
    PLAYMUSIC.playerLayer.frame = CGRectMake(0, 0, self.bounds.size.width, self.frame.size.height);
    
}



#pragma mark - 轻拍方法
- (void)tapAction:(UITapGestureRecognizer *)tap {
    if (_isHiddenDownView) {
        _downView.hidden = YES;
    } else {
        _downView.hidden = NO;
        [self performSelector:@selector(dismissdownView) withObject:nil afterDelay:5];
    }
    _isHiddenDownView = !_isHiddenDownView;

}

- (void)dismissdownView {
    _downView.hidden = YES;
    _isHiddenDownView = NO;
}



#pragma mark - slider 点击方法
- (void)sliderAction:(UISlider *)slider {
    
    [PLAYMUSIC seekToTimePalyVideo:slider.value];
}



#pragma mark - button点击
- (void)centerButtonAction:(UIButton *)button {
    [PLAYMUSIC playMV];
    _isPlay = YES;
    [_playOrPauseButton setBackgroundImage:[UIImage imageNamed:@"iconfont-suopingzanting"] forState:(UIControlStateNormal)];
    [self performSelector:@selector(dismissdownView) withObject:nil afterDelay:5];
    button.hidden = YES;
}

- (void)playOrPauseButtonAction:(UIButton *)button {
    if (_isPlay) {
        [PLAYMUSIC pauseMV];
        _centerButton.hidden = NO;
        [_playOrPauseButton setBackgroundImage:[UIImage imageNamed:@"iconfont-bofang-2"] forState:(UIControlStateNormal)];
    } else {
        [PLAYMUSIC playMV];
        [self performSelector:@selector(dismissdownView) withObject:nil afterDelay:5];
        _centerButton.hidden = YES;
        [_playOrPauseButton setBackgroundImage:[UIImage imageNamed:@"iconfont-suopingzanting"] forState:(UIControlStateNormal)];
    }
    
    _isPlay = !_isPlay;
}




- (void)fullScreenButtonAction:(UIButton *)button {
    
    [self.delegate fullScreenButtonActionFull:_buttonTo fullButton:button];
    
    [self createFram];

    
}

- (void)buttonToAction:(UIButton *)button {
    
    [PLAYMUSIC pauseMV];
    [self.delegate buttonToActionClick];
}

- (void)fullScreenButtonFull {
    if ([UIDevice currentDevice].orientation != UIDeviceOrientationPortrait) {
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        _buttonTo.hidden = NO;
        PLAYMUSIC.playerLayer.frame = CGRectMake(0, 0, self.bounds.size.width, self.frame.size.height);
        self.frame = CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight / 3);
        [self createFram];
        
    } else {
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        _buttonTo.hidden = YES;
        self.frame = CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight);
        PLAYMUSIC.playerLayer.frame = CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight);
        [self createFram];
        
    }
}



+ (PlayMusicVideoView *)playMusicVideoViewWithFrame:(CGRect)frame {
    return [[PlayMusicVideoView alloc] initWithFrame:frame];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor blackColor];
        
        _isPlay = YES;
        _isHiddenDownView = YES;
        
        PLAYMUSIC.playerLayer.frame = CGRectMake(0, 0, self.bounds.size.width, self.frame.size.height);
        [self.layer insertSublayer:PLAYMUSIC.playerLayer atIndex:0];
        
        [self createSubView];
    }
    return self;
}

- (void)setSongsModel:(WXLSongsModel *)songsModel {
    
    if (_songsModel != songsModel) {
        _songsModel = songsModel;
    }
    
    [self performSelector:@selector(dismissdownView) withObject:nil afterDelay:5];
    _centerButton.hidden = YES;;
    _isPlay = YES;
    [_playOrPauseButton setBackgroundImage:[UIImage imageNamed:@"iconfont-suopingzanting"] forState:(UIControlStateNormal)];
    [self createPlay];
}

- (void)createPlay {
    
    _playTimeSlider.maximumValue = _songsModel.mvListDuration;
    
    NSString *durationT = [NSString stringWithFormat:@"%02d:%02d", (int)_songsModel.mvListDuration / 60, (int)_songsModel.mvListDuration % 60];
    _rightSumTimeLabel.text = durationT;
    
    [PLAYMUSIC playMovieFromUrl:_songsModel.mvListUrl];
    [PLAYMUSIC playMV];
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
